package com.extension.company.common.utils;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class Utils {
    public static final String RESPONSE_METHOD = "method";
    public static final String RESPONSE_CONTENT = "content";
    public static final String RESPONSE_ERRCODE = "errcode";
    protected static final String ACTION_LOGIN = "com.baidu.pushdemo.action.LOGIN";
    public static final String ACTION_MESSAGE = "com.baiud.pushdemo.action.MESSAGE";
    public static final String ACTION_RESPONSE = "bccsclient.action.RESPONSE";
    public static final String ACTION_SHOW_MESSAGE = "bccsclient.action.SHOW_MESSAGE";
    protected static final String EXTRA_ACCESS_TOKEN = "access_token";
    public static final String EXTRA_MESSAGE = "message";

    public static String logStringCache = "";

    public static String getMetaValue(Context context, String metaKey) {
        Bundle metaData = null;
        String apiKey = null;
        if (context == null || metaKey == null) {
            return null;
        }
        try {
            ApplicationInfo ai = context.getPackageManager()
                    .getApplicationInfo(context.getPackageName(),
                            PackageManager.GET_META_DATA);
            if (null != ai) {
                metaData = ai.metaData;
            }
            if (null != metaData) {
                apiKey = metaData.getString(metaKey);
            }
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return apiKey;
    }

    public static boolean hasBind(Context context) {
        SharedPreferences sp = PreferenceManager
                .getDefaultSharedPreferences(context);
        String flag = sp.getString("bind_flag", "");
        if ("ok".equalsIgnoreCase(flag)) {
            return true;
        }
        return false;
    }

    public static void setBind(Context context, boolean flag) {
        String flagStr = "not";
        if (flag) {
            flagStr = "ok";
        }
        SharedPreferences sp = PreferenceManager
                .getDefaultSharedPreferences(context);
        Editor editor = sp.edit();
        editor.putString("bind_flag", flagStr);
        editor.commit();
    }

    public static List<String> getTagsList(String originalText) {
        if (originalText == null || originalText.equals("")) {
            return null;
        }
        List<String> tags = new ArrayList<String>();
        int indexOfComma = originalText.indexOf(',');
        String tag;
        while (indexOfComma != -1) {
            tag = originalText.substring(0, indexOfComma);
            tags.add(tag);

            originalText = originalText.substring(indexOfComma + 1);
            indexOfComma = originalText.indexOf(',');
        }

        tags.add(originalText);
        return tags;
    }

    public static String getLogText(Context context) {
        SharedPreferences sp = PreferenceManager
                .getDefaultSharedPreferences(context);
        return sp.getString("log_text", "");
    }

    public static void setLogText(Context context, String text) {
        SharedPreferences sp = PreferenceManager
                .getDefaultSharedPreferences(context);
        Editor editor = sp.edit();
        editor.putString("log_text", text);
        editor.commit();
    }

    /**
     * 根据图片高度设置View高度 group
     *
     * @param context context
     * @param view    要设置的视图View
     * @param bWidth  图片的宽度
     * @param bHeight 图片的高度
     */
    public static void setPicHeight(Context context, View view, int bWidth,
                                    int bHeight) {
        try {
            // 获取屏幕当前分辨率
            DisplayMetrics dm = new DisplayMetrics();
            dm = context.getResources().getDisplayMetrics();
            float screenWidth = dm.widthPixels;
            float screenHeight = dm.heightPixels;
            float socalW = screenWidth / bWidth;
            float socalH = screenHeight / bHeight;
            float socal = socalW < socalH ? socalW : socalH;
            int height = (int) (bHeight * socal);
            view.setLayoutParams(new RelativeLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, height));// 设置banner高度
        } catch (Exception e) {
            view.setLayoutParams(new RelativeLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, bHeight));// 设置banner高度
        }
    }

    /**
     * 设置继续滑动高度
     *
     * @param context
     * @param view
     * @param bWidth
     * @param bHeight
     */
    public static void setPicHeightAd(Context context, View view, int bWidth,
                                      int bHeight) {
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view
                .getLayoutParams();
        try {
            // 获取屏幕当前分辨率
            DisplayMetrics dm = new DisplayMetrics();
            dm = context.getResources().getDisplayMetrics();
            float screenWidth = dm.widthPixels;
            float screenHeight = dm.heightPixels;
            float socalW = screenWidth / bWidth;
            float socalH = screenHeight / bHeight;
            float socal = socalW < socalH ? socalW : socalH;
            int height = (int) (bHeight * socal);
            layoutParams.width = LayoutParams.WRAP_CONTENT;
            layoutParams.height = height;
        } catch (Exception e) {
            layoutParams.width = LayoutParams.WRAP_CONTENT;
            layoutParams.height = bHeight;
        }
        view.setLayoutParams(layoutParams);
    }

    /**
     * 根据图片高度设置View高度 group
     *
     * @param context context
     * @param view    要设置的视图View
     * @param bWidth  图片的宽度
     * @param bHeight 图片的高度
     */
    public static void setPicHeightForActivity(Context context, View view,
                                               int bWidth, int bHeight) {
        try {
            // 获取屏幕当前分辨率
            DisplayMetrics dm = new DisplayMetrics();
            dm = context.getResources().getDisplayMetrics();
            float screenWidth = dm.widthPixels - Dp2Px(context, 20);
            float screenHeight = dm.heightPixels;
            float socalW = screenWidth / bWidth;
            float socalH = screenHeight / bHeight;
            float socal = socalW < socalH ? socalW : socalH;
            int height = (int) (bHeight * socal);
            view.setLayoutParams(new RelativeLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, height));// 设置banner高度
        } catch (Exception e) {
            view.setLayoutParams(new RelativeLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, bHeight));// 设置banner高度
        }
    }

    /**
     * 减掉总间距，一行显示几个,父视图是RelativeLayout
     *
     * @param context
     * @param view
     * @param bWidth
     * @param bHeight
     * @param gapCount 一行显示几个
     * @param gapWidth 总间距
     */
    public static void setPicHeightEx(Context context, View view, int bWidth,
                                      int bHeight, float gapCount, float gapWidth) {
        try {
            // 获取屏幕当前分辨率
            DisplayMetrics dm = new DisplayMetrics();
            dm = context.getResources().getDisplayMetrics();
            float screenWidth = (dm.widthPixels - Dp2Px(context, gapWidth))
                    / gapCount;
            float screenHeight = dm.heightPixels;
            float socalW = screenWidth / bWidth;
            float socalH = screenHeight / bHeight;
            float socal = socalW < socalH ? socalW : socalH;
            int height = (int) (bHeight * socal);
            view.setLayoutParams(new RelativeLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, height));// 设置banner高度
        } catch (Exception e) {
            view.setLayoutParams(new RelativeLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, bHeight));// 设置banner高度
        }
    }

    /**
     * 减掉总间距，一行显示几个,父视图是LinearLayout
     *
     * @param context
     * @param view
     * @param bWidth
     * @param bHeight
     * @param gapCount 一行显示几个
     * @param gapWidth 总间距
     */
    public static void setPicHeightExLinearLayoutM(Context context, View view, int bWidth,
                                                   int bHeight, float gapCount, float gapWidth) {
        try {
            // 获取屏幕当前分辨率
            DisplayMetrics dm = new DisplayMetrics();
            dm = context.getResources().getDisplayMetrics();
            float screenWidth = (dm.widthPixels - Dp2Px(context, gapWidth))
                    / gapCount;
            float screenHeight = dm.heightPixels;
            float socalW = screenWidth / bWidth;
            float socalH = screenHeight / bHeight;
            float socal = socalW < socalH ? socalW : socalH;
            int height = (int) (bHeight * socal);
            view.setLayoutParams(new LinearLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, height));// 设置banner高度
        } catch (Exception e) {
            view.setLayoutParams(new LinearLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, bHeight));// 设置banner高度
        }
    }

    /**
     * 减掉总间距，一行显示几个,父视图是LinearLayout
     *
     * @param context
     * @param view
     * @param bWidth
     * @param bHeight
     * @param gapCount
     * @param gapWidth
     */
    public static void setPicHeightExLinearLayout(Context context, View view,
                                                  int bWidth, int bHeight, float gapCount, float gapWidth) {
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) view
                .getLayoutParams();
        try {
            // 获取屏幕当前分辨率
            DisplayMetrics dm = new DisplayMetrics();
            dm = context.getResources().getDisplayMetrics();
            float screenWidth = (dm.widthPixels - Dp2Px(context, gapWidth))
                    / gapCount;
            float screenHeight = dm.heightPixels;
            float socalW = screenWidth / bWidth;
            float socalH = screenHeight / bHeight;
            float socal = socalW < socalH ? socalW : socalH;
            int height = (int) (bHeight * socal);
            layoutParams.width = LayoutParams.MATCH_PARENT;
            layoutParams.height = height;
        } catch (Exception e) {
            layoutParams.width = LayoutParams.MATCH_PARENT;
            layoutParams.height = bHeight;
        }
        view.setLayoutParams(layoutParams);
    }

    /**
     * 减掉总间距，一行显示几个,父视图是LinearLayout,并返回高度
     *
     * @param context
     * @param view
     * @param bWidth
     * @param bHeight
     * @param gapWidth
     */
    public static float getPicHeightExLinearLayout(Context context, View view,
                                                   int bWidth, int bHeight, float gapWidth) {
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) view
                .getLayoutParams();
        try {
            // 获取屏幕当前分辨率
            DisplayMetrics dm = new DisplayMetrics();
            dm = context.getResources().getDisplayMetrics();
            float screenWidth = (dm.widthPixels - Dp2Px(context, gapWidth)) * 0.5f;
            layoutParams.width = (int) screenWidth;
            layoutParams.height = (int) screenWidth;
        } catch (Exception e) {
            layoutParams.width = LayoutParams.WRAP_CONTENT;
            layoutParams.height = LayoutParams.WRAP_CONTENT;
        }
        view.setLayoutParams(layoutParams);
        return layoutParams.height - 1;
    }

    public static void setPicHeightExLinearLayout1(Context context, View view, int bHeight) {
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) view
                .getLayoutParams();
        try {
            layoutParams.height = bHeight;
        } catch (Exception e) {
            layoutParams.height = bHeight;
        }
        view.setLayoutParams(layoutParams);
    }

    /**
     * 图片的px转为手机中px
     *
     * @param context
     * @param bWidth
     * @return
     */
    public static float getWidth(Context context,
                                 int bWidth) {
        float screenWidth = bWidth;
        try {
            // 获取屏幕当前分辨率
            DisplayMetrics dm = new DisplayMetrics();
            dm = context.getResources().getDisplayMetrics();
            screenWidth = dm.widthPixels * ((float) bWidth / 640f);
            System.out.println("screenWidth:" + screenWidth);
        } catch (Exception e) {
        }
        return screenWidth;
    }

    /**
     * dp转px
     *
     * @param context
     * @param dp
     * @return
     */
    public static int Dp2Px(Context context, float dp) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }

    /**
     * 获取屏幕当前分辨率
     *
     * @param context
     * @return
     */
    public static float getScreenWidth(Context context) {
        try {
            // 获取屏幕当前分辨率
            DisplayMetrics dm = new DisplayMetrics();
            dm = context.getResources().getDisplayMetrics();
            float screenWidth = dm.widthPixels;
            // float screenHeight = dm.heightPixels;
            return screenWidth;
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 强制隐藏键盘
     *
     * @param v
     */
    public static void hideSoftInput(Context context, View v) {
        InputMethodManager imm = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(v, InputMethodManager.SHOW_FORCED);
        imm.hideSoftInputFromWindow(v.getWindowToken(), 0); // 强制隐藏键盘
    }

    /**
     * 以最省内存的方式读取本地资源的图片
     *
     * @param context
     * @param resId
     * @return
     */
    public static Bitmap readBitMap(Context context, int resId) {
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
        opt.inPurgeable = true;
        opt.inInputShareable = true;
        // 获取资源图片
        InputStream is = context.getResources().openRawResource(resId);
        return BitmapFactory.decodeStream(is, null, opt);
    }

    /**
     * 获取总页数
     *
     * @param amount   总条数
     * @param capacity 一页多少条
     * @return
     */
    public static int getAllPage(int amount, int capacity) {
        int sum = 0;
        try {
            sum = amount / capacity + (amount % capacity > 0 ? 1 : 0);
        } catch (Exception e) {
            sum = 0;
        }
        return sum;
    }

    /*
     * 显示window
     */
    public static void showWindow(Window win) {
        win.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams lp = win.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        win.setAttributes(lp);
    }
    
    //获取手机状态栏高度
    public static int getStatusBarHeight(Context context) {
        Class<?> c = null;
        Object obj = null;
        Field field = null;
        int x = 0, statusBarHeight = 0;
        try {
            c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            statusBarHeight = context.getResources().getDimensionPixelSize(x);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return statusBarHeight;
    }

    /**
     * 设置页面最外层布局 FitsSystemWindows 属性
     * @param activity
     * @param value
     */
    public static void setFitsSystemWindows(Activity activity, boolean value) {
        ViewGroup contentFrameLayout = (ViewGroup) activity.findViewById(android.R.id.content);
        View parentView = contentFrameLayout.getChildAt(0);
        if (parentView != null && Build.VERSION.SDK_INT >= 14) {
            parentView.setFitsSystemWindows(value);
        }
    }
}
